<template>
    <div class="app-container">
        <el-form :inline="true" label-position="right" ref="queryRef" :model="params" label-width="200px" :rules="rules">
            <div class="form-inline">
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="钻孔依托的项目：" class="form-item" prop="projectName">
                            <el-input v-model="params.projectName" placeholder="" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="土动力试验参数：" class="form-item" prop="soilDynamic">
                            <el-select placeholder="请选择" class="form-select" v-model="params.soilDynamic">
                                <el-option v-for="item in soilDynamicOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="孔位：" class="form-location">
                            <el-form-item label="经度" label-width="40px">
                                <el-form-item label-width="0px" prop="startHlLongitude">
                                    <el-input v-model="params.startHlLongitude" placeholder="请输入" class="el-form-longitude" clearable />
                                </el-form-item>
                                <span class="line" style="padding:0 3px;">--</span>
                                <el-form-item label-width="0px" prop="endHlLongitude">
                                    <el-input v-model="params.endHlLongitude" placeholder="请输入" class="el-form-longitude" clearable />
                                </el-form-item>
                            </el-form-item>
                              &emsp;
                            <el-form-item label="纬度" label-width="40px">
                                <el-form-item label-width="0px" prop="startHlLatitude">
                                    <el-input v-model="params.startHlLatitude" placeholder="请输入" class="el-form-longitude" clearable />
                                </el-form-item>
                                <span class="line" style="padding:0 3px;">--</span>
                                    <el-form-item label-width="0px" prop="endHlLatitude">
                                        <el-input v-model="params.endHlLatitude" placeholder="请输入" class="el-form-longitude" clearable />
                                    </el-form-item>
                            </el-form-item>
                          <!-- <el-form-item label="经度" label-width="40px" prop="hlLongitude">
                              <el-input v-model="params.hlLongitude" placeholder="" class="el-form-longitude" clearable />
                          </el-form-item>&emsp;
                          <el-form-item label="纬度" label-width="40px" prop="hlLatitude">
                              <el-input v-model="params.hlLatitude" placeholder="" class="el-form-latitude" clearable />
                          </el-form-item> -->
                      </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="剪切波实测值：" class="form-item" prop="measuredValues">
                            <el-select placeholder="请选择" class="form-select" v-model="params.measuredValues" clearable>
                                <el-option v-for="item in measuredValuesOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="数据类别：" class="form-item" prop="dataType">
                            <el-select v-model="params.dataType" placeholder="请选择" class="form-select">
                                <el-option v-for="item in dataTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="场地类别：" class="form-item" prop="siteType">
                            <el-select v-model="params.siteType" placeholder="请选择" class="form-select">
                                <el-option v-for="item in siteTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="end">
                    <el-form-item class="bottom-button">
                        <!-- <el-button type="primary" @click="onImportParms()">导入</el-button> -->
                        <el-button type="primary" @click="onSearch">查询</el-button>
                        <el-button type="primary" @click="onRest">重置</el-button>
                        <el-button type="primary" @click="onExport">导出</el-button>
                    </el-form-item>
                </el-row>
            </div>
        </el-form>

        <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="列表展示" name="first">
                <div class="table-wrapper">
                    <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
                        @selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7', }"
                        :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }" row-key="pfId">
                        <!-- <el-table-column type="selection" :reserve-selection="true" width="55" align="center" /> -->
                        <el-table-column prop="name" header-align="center" align="center" label="项目名称" width="200" show-overflow-tooltip />
                        <el-table-column prop="projectName" header-align="center" align="left" label="钻孔依托的项目"
                            width="290">
                            <template #default="scope">
                                <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">
                                    {{ scope.row.projectName }}
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="孔位" header-align="center" align="center">
                            <el-table-column prop="hlLongitude" label="经度" header-align="center" align="center"
                                width="110" />
                            <el-table-column prop="hlLatitude" label="纬度" header-align="center" align="center"
                                width="110" />
                        </el-table-column>
                        <el-table-column prop="boreholeNumber" header-align="center" align="center" label="钻孔编号" />
                        <el-table-column prop="groundElevation" header-align="center" align="center" label="地面高程" />
                        <el-table-column prop="drillingDepth" header-align="center" align="center" label="钻孔深度" />
                        <el-table-column prop="y06Exist" header-align="center" align="center" label="土动力试验参数">
                            <template #default="scope">
                                {{ scope.row.y06Exist === '1' ? '存在' : '不存在' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="y08Exist" header-align="center" align="center" label="剪切波实测值">
                            <template #default="scope">
                                {{ scope.row.y08Exist === '1' ? '存在' : '不存在' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="fieldType" header-align="center" align="center" label="场地类别">
                            <template #default="{ row }">
                                {{ mapSiteType[row.fieldType] || '' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="model" header-align="center" align="center" label="数据类别" />
                    </el-table>
                    <div class="paging">
                        <el-pagination background v-model:current-page="pagination.pageNo" :layout="layout"
                            :page-size="pagination.pageSize" :total="pagination.total" @current-change="handleCurrentChange"
                            @size-change="handleSizeChange" />
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="地图展示" name="second">
              <!--地图-->
              <DrillingInfoCompreQueryMap v-show="activeName=='second'"
                                          :dataList="mapDataList" ref="mapRef"
                                          @getResultsByGeomText="getResultsByGeomText" @mapLoading="mapLoading" @viewProject="viewProject"
              ></DrillingInfoCompreQueryMap>
            </el-tab-pane>
        </el-tabs>

        <!-- 导入弹框 -->
        <ImportData v-if="dialogVisible" v-model="dialogVisible" ref="uploadRef" :downloadFileName="downloadFileName"
            :uploadUrl="uploadFileUrl" @importSuccess="onImport"></ImportData>
    </div>
</template>

<script setup name="compreQuery">
//地图
import DrillingInfoCompreQueryMap from '@/map/drillingInfoCompreQuery/map.vue';
import { queryResultsByGeomText,queryListResultsByGeomText } from "@/api/drillingInfoCompreQuery/drillingInfoCompreQuery.js";
import { ref } from "vue";
// 引入数据导入弹框组件
import ImportData from '@/components/ImportData';
// 文件下载
import { downloadGet } from '@/utils/request';
// 引入接口
import {
    queryData, //分页
    queryMapData,
    // exportData,// 导出
} from "@/api/drillingInfoCompreQuery/drillingInfoCompreQuery.js";
// 引入表单验证规则
import {
    validateLon, //验证经度
    validateLat, //验证纬度
} from "@/components/FormValidate";
// 引入store
import useDictStore from "@/store/modules/dict";

//import cloneDeep from 'lodash/cloneDeep';


// store对象
const dictStore = useDictStore();
// 场地类别map
let mapSiteType = dictStore.ArrayToMap(dictStore.siteTypeOptions);

// 当前实例对象
const { proxy } = getCurrentInstance()
// 全局路由对象
const router = useRouter();

// 定义变量
const data = reactive({
    params: {
        projectName: "", //钻孔依托的项目
        startHlLongitude: "", //起始经度
        endHlLongitude: "", //结束经度
        startHlLatitude: "", //起始纬度
        endHlLatitude: "", //结束经度
        //hlLongitude: "",//孔位经度
        //hlLatitude: "",//孔位纬度
        dataType: "",//数据类别
        siteType: "",//场地类别
        soilDynamic: "", //土动力试验参数：
        measuredValues: '',//剪切波实测值：
    },
    rules: {
        startHlLongitude: [
            { message: "请输入开始经度", trigger: "blur" },
            {
                validator: validateLon,
                trigger: ["change", "blur"],
            },
        ],
        endHlLongitude: [
            { message: "请输入结束经度", trigger: "blur" },
            {
                validator: validateLon,
                trigger: ["change", "blur"],
            },
        ],
        startHlLatitude: [
            { message: "请输入开始纬度", trigger: "blur" },
            {
                validator: validateLat,
                trigger: ["change", "blur"],
            },
        ],
        endHlLatitude: [
            { message: "请输入结束纬度", trigger: "blur" },
            {
                validator: validateLat,
                trigger: ["change", "blur"],
            },
        ]
    },
    // 土动力实验参数
    soilDynamicOptions: dictStore.soilDynamicOptions || [],
    // 数据类别，候选值：安评成果库、区评成果库、小区划成果库，数据管理系统
    dataTypeOptions: dictStore.dataTypeOptions || [],
    // 场地类别，候选值：I1类场地、Ⅱ类场地、Ⅲ类场地、Ⅳ类场地、I0场地
    siteTypeOptions: dictStore.siteTypeOptions || [],
    // 剪切波实测值选项
    measuredValuesOptions: dictStore.measuredValuesOptions || [],

    //表格
    tableData: [],
    // 分页, 控件
    layout: "prev, pager, next, jumper, sizes, total",
    // 分页, 参数
    pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
    },
});
const {
    params,
    pagination,
    layout,
    rules,
    soilDynamicOptions,
    siteTypeOptions,
    measuredValuesOptions,
    dataTypeOptions,
    tableData,
} = toRefs(data);

// 文件上传
// 上传组件对象
const uploadRef = ref();
// 是否显示弹框
const dialogVisible = ref(false);
// 文件上传地址
const uploadFileUrl = "/drillHoleQuery/uploadDetails";
// 模板文件名称
const downloadFileName = '钻孔数据导入模板.xlsx';
// 上传成功回调
const onImport = (response, uploadFile, uploadFiles) => {
    // console.log(response);
}

// tab当前项
const activeName = ref("first");
const isRefesh = ref(true);
const handleClick = (tab, event) => {
    //console.log(activeName.value)
    //console.log(proxy.$refs['mapRef'],'===')
    if(activeName.value=="second"&&isRefesh.value) {
        isRefesh.value=false;
        proxy.$refs['mapRef'].switchTabMap();
    }else{
        pagination.value.pageNo = 1;
    }
    onSearch();
}

const lastSearchParams=ref({});
const currentGemo=ref();

// 表格对象
const multipleTableRef = ref();
// 当前行
const curTableRow = ref(null);
// 表格选择行数据
const multipleSelection = ref([]);
const ids = ref([])
const multiple = ref(true)
// 表格多选事件监听
const handleSelectionChange = (val) => {
    ids.value = val.map(item => item.pfId);
    multiple.value = !val.length;
    multipleSelection.value = val;
    // 当前行
    curTableRow.value = val;
};
// 分页, 每页显示行数修改
const handleSizeChange = (val) => {
    // 每页条数
    pagination.value.pageSize = val;
    // 当前页数置为1
    pagination.value.pageNo = 1;
    // 查询
    onSearch();
};
// 分页, 当前页数修改
const handleCurrentChange = (val) => {
    // 当前页数
    pagination.value.pageNo = val;
    // 查询
    onSearch();
};

// 查看跳转信息页面
const viewProject = (row) => {
    if (row.pfId) {
        router.push({
            path: '/drillingInfoCompreQuery/drillHoleDisplay', query: {
                id: row.pfId, // row.projectId
                type: row.model
            }
        });
    } else {
        proxy.$modal.msgWarning('当前行数据编号为空!');
    }
}

// 导入事件监听
const onImportParms = () => {
    dialogVisible.value = true
}
// 查询
const onSearch = () => {
if(activeName.value=='first'){    
    proxy.$modal.loading('加载中！');
    //lastSearchParams.value=params.value;
    lastSearchParams.value=JSON.parse(JSON.stringify(params.value));
    queryData({
        ...params.value,
        page: pagination.value.pageNo,
        rows: pagination.value.pageSize,
        geom:currentGemo.value
    }).then(res => {
        proxy.$modal.closeLoading();
        if (res.code === 200 && res.data) {
            // 分页总数
            pagination.value.total = res.data.total;
            tableData.value = res.data.rows.length ? res.data.rows : [];
        } else {
            // 分页总数
            pagination.value.total = 0;
            tableData.value = [];
        }
    }).catch(err => {
        proxy.$modal.closeLoading();
        console.log(err);
    });
}else{
    const query = {
        ...params.value,
        //param:lastSearchParams.value,
        geom: currentGemo.value,
    }
    //currentGemo.value=geomText;
    mapLoading(true);
    //地图圈选查询
    queryResultsByGeomText(query).then((res) => {
        if (res.code === 200) {
            mapDataList.value = res.data;
            if (res.data != null && res.data.length > 0) {
                let length = res.data.length;
                // proxy.$modal.msgSuccess("查询到" + length + "条数据.");
            } else {
                proxy.$modal.msgWarning('圈选范围无查询结果！');
            }
        } else {
            proxy.$modal.msgWarning('查询失败！');
        }
        mapLoading(false);
    }).catch(err => {
        console.log(err);
        proxy.$modal.msgError('查询失败！');
        mapLoading(false);
    });
}
    /*proxy.$modal.loading('加载中！');
    queryMapData({
        ...params.value,

    }).then(res => {
        proxy.$modal.closeLoading();
        if (res.code === 200) {
            //调用清空地图方法
            proxy.$refs['mapRef'].clearMapQX();
            mapDataList.value = res.data;
        } else {
            proxy.$modal.msgWarning('查询失败！');
        }
        mapLoading(false);
    }).catch(err => {
        proxy.$modal.closeLoading();
        console.log(err);
    });*/
}
// 重置
const onRest = () => {
    proxy.resetForm("queryRef");
    pagination.value.pageNo = 1;
    proxy.$refs['mapRef'].clearMapQX();
    currentGemo.value=null;
    lastSearchParams.value=null;
    onSearch();
};
//导出
const onExport = () => {
    // console.log(multiple.value,ids.value);
    // if(activeName.value=='first'&& !multiple.value){
    //     //proxy.$refs['listTable'].clearSelection()
    //     downloadGet('/drillHoleQuery/exportData', { ids:ids.value }, '钻孔信息.xls')//.join(",")
    //     multipleTableRef.value.clearSelection();
    // }else{
        
    // }
    downloadGet('/drillHoleQuery/exportData', { ...params.value }, '钻孔信息.xls')
}

//地图传参--start
const mapDataList = ref([]);//地图圈选查询结果列表
//地图圈选查询
const getResultsByGeomText = (geomText) => {
  if(geomText!=null && geomText!="") {
      const query = {
          // ...params.value,
          //param:lastSearchParams.value,
          ...lastSearchParams.value,
          geom: geomText,
      }
      console.log("testtest:::");
      console.log(lastSearchParams.value);
      currentGemo.value=geomText;
      mapLoading(true);
      //地图圈选查询
      queryResultsByGeomText(query).then((res) => {
          if (res.code === 200) {
              mapDataList.value = res.data;
              if (res.data != null && res.data.length > 0) {
                  let length = res.data.length;
                //   proxy.$modal.msgSuccess("查询到" + length + "条数据.");
              } else {
                  proxy.$modal.msgWarning('圈选范围无查询结果！');
              }
          } else {
              proxy.$modal.msgWarning('查询失败！');
          }
          mapLoading(false);
      }).catch(err => {
          console.log(err);
          proxy.$modal.msgError('查询失败！');
          mapLoading(false);
      });

      //lastSearchParams.value=params.value;
      //lastSearchParams.value=_.clone(params.value);
      queryData({
          ...params.value,
          page: pagination.value.pageNo,
          rows: pagination.value.pageSize,
          geom:currentGemo.value
      }).then(res => {
          proxy.$modal.closeLoading();
          if (res.code === 200 && res.data) {
              // 分页总数
              pagination.value.total = res.data.total;
              tableData.value = res.data.rows.length ? res.data.rows : [];
          } else {
              // 分页总数
              pagination.value.total = 0;
              tableData.value = [];
          }
      }).catch(err => {
          proxy.$modal.closeLoading();
          console.log(err);
      });

      //地图圈选查询列表展示
      /*const queryList = {
          // ...params.value,
          geom: geomText,
          page: pagination.value.pageNo,
          rows: pagination.value.pageSize
      }
      queryListResultsByGeomText(queryList).then((res) => {
          proxy.$modal.closeLoading();
          if (res.code === 200 && res.data) {
              // 分页总数
              pagination.value.total = res.data.total;
              tableData.value = res.data.rows.length ? res.data.rows : [];
          } else {
              // 分页总数
              pagination.value.total = 0;
              tableData.value = [];
          }
      }).catch(err => {
          proxy.$modal.closeLoading();
          console.log(err);
      });*/
  }
};
//查询状态
const mapLoading = (bool) => {
  if(bool){
    proxy.$modal.loading("正在查询，请稍候...");
  }else{
    proxy.$modal.closeLoading();
  }
};
//地图传参--end

// 挂载
onMounted(() => {
    // 查询
    onSearch();
})
</script>

<style lang="scss" scoped>
.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 32px;
    font-weight: 600;
}

.form-inline {
    :deep(.el-form-item__error) {
        z-index: 1;
    }

    .form-item {
        :deep(.el-form-item__content) {
            width: 300px;
        }

        .form-select {
            width: 300px;
        }

        .form-date {
            width: 130px;
        }
    }

    .form-location-p {
        margin-left: 138px;

        .el-form-longitude-p,
        .el-form-latitude-p {
            width: 105px;
        }
    }

    .form-location {
        .el-form-item {
            margin-right: 0;
        }

        .el-form-longitude,
        .el-form-latitude {
            width: 100px;
        }
    }
}

.paging {
  padding: 20px 10%;
  .el-pagination{
    justify-content: center;
  }
}

.downloadModel {
    font-size: 16px;
    line-height: 60px;

    span {
        color: #107ce5;
        cursor: pointer;
    }
}
</style>